package cn.wolfcode.wolf2w.member.service.impl;

import cn.wolfcode.wolf2w.common.core.utils.StringUtils;
import cn.wolfcode.wolf2w.common.redis.service.RedisService;
import cn.wolfcode.wolf2w.common.redis.util.RedisKeys;
import cn.wolfcode.wolf2w.member.api.domain.UserFoandfan;
import cn.wolfcode.wolf2w.member.mapper.UserFoandfanMapper;
import cn.wolfcode.wolf2w.member.query.UserFoandfanQuery;
import cn.wolfcode.wolf2w.member.service.IUserFoandfanService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 用户关注与粉丝Service业务层处理
 * 
 * @author dalang
 * @date 2023-12-03
 */
@Service
@Transactional
public class UserFoandfanServiceImpl extends ServiceImpl<UserFoandfanMapper,UserFoandfan> implements IUserFoandfanService {
    @Autowired
    private RedisService redisService;

    @Override
    public IPage<UserFoandfan> queryPage(UserFoandfanQuery qo) {
        IPage<UserFoandfan> page = new Page<>(qo.getCurrentPage(), qo.getPageSize());
        return lambdaQuery()
                .page(page);
    }

    @Override
    public void initStrategyHash(Long uid) {
        String fokey = RedisKeys.FOLLOWS_SET.join(uid.toString());
        String fankey = RedisKeys.FANS_SET.join(uid.toString());

        if (!redisService.hasKey(fokey)) {
            String foids = lambdaQuery().eq(UserFoandfan::getUid, uid).list().get(0).getFoids();
            if (StringUtils.hasText(foids)) {
                Set<Long> foset = Arrays.stream(foids.split(",")).map(Long::parseLong).collect(Collectors.toSet());
                redisService.setCacheSet(fokey,foset);
            }
        }

        if (!redisService.hasKey(fankey)) {
            String fanids = lambdaQuery().eq(UserFoandfan::getUid, uid).list().get(0).getFanids();
            if (StringUtils.hasText(fanids)) {
                Set<Long> fanset = Arrays.stream(fanids.split(",")).map(Long::parseLong).collect(Collectors.toSet());
                redisService.setCacheSet(fankey,fanset);
            }
        }
    }
}
